package br.boicotando.persistencia;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import br.boicotando.shared.Util;

@Entity
@Table(name="SETOR_CATEGORIA")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TIPO", discriminatorType = DiscriminatorType.STRING, length = 3)
@DiscriminatorValue("SET")
@SuppressWarnings("serial")
public class ESetor implements Serializable {

	@Id
	@Column(name = "ID", length = 50, nullable = false, updatable = false)
	private String id;
	@Column(name = "NOME", length = 40, nullable = false, unique = true)
	private String nome;
	@OneToMany(mappedBy = "setor", cascade = {CascadeType.ALL})
	private Set<ECategoria> categorias;
	
	public ESetor() {
		id = Util.getAUID();
		categorias = new HashSet<ECategoria>();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public boolean adicionaCategoria(ECategoria c) {
		boolean adicionou = categorias.add(c);
		if (!equals(c.getSetor())) {
			c.setSetor(this);
		}
		return adicionou;
	}

	public boolean contemCategoria(ECategoria c) {
		return categorias.contains(c);
	}

	public ECategoria[] getCategorias(ECategoria[] a) {
		return categorias.toArray(a);
	}

	public boolean removeCategoria(ECategoria c) {
		boolean removeu = categorias.remove(c);
		if (equals(c.getSetor())) {
			c.setSetor(null);
		}
		return removeu;
	}

	public void removeCategorias() {
		for (ECategoria categoria : categorias) {
			removeCategoria(categoria);
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ESetor other = (ESetor) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

}
